﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AttributeRouting;
using AttributeRouting.Web.Mvc;
using Newtonsoft.Json.Linq;

using Invoicing.Model.Results;
using Invoicing.Model.Orders;
using Invoicing.Logic.Orders;
namespace Invoicing.Web.Management.Areas.Orders.Controllers
{
    [RouteArea("Orders")]
    [RoutePrefix("BookOrder")]
    [Authorize]
    public class BookOrderApiController : ApiController
    {
        [Route("SaveOrders")]
        [HttpPost]
        public JsonEntity<BookOrderModel> SaveOrders(JObject request)
        {
            string errinfo = "对不起！单据保存失败，出错原因：";
            try
            {
                #region 收集参数
                var order = new BookOrderModel() { Items = new BookOrderDetailCollection() };
                var items = request.GetValue("orderItems");
                if (items != null)
                {
                    order.NoteDate = request.Value<DateTime>("orderDate");
                    order.CustomerID = request.Value<int>("customerID");
                    order.OperatorUserID = Web.Global.WebContext.CurrentUser.ID;
                    order.Method = request.Value<int>("method");
                    order.OrderNo = request.Value<string>("orderNo");
                    foreach (var it in items)
                    {
                        var bodm = new BookOrderDetailModel()
                        {
                            ProductID = it.Value<int>("productID"),
                            MaterialID = it.Value<int>("materialID"),
                            ProcessID = it.Value<int>("processID"),
                            Size = it.Value<string>("size"),
                            Quantity=it.Value<decimal>("quantity")
                        };
                        order.Items.Add(bodm);
                    }
                }
                else
                    throw new Utils.InvoicingException("没有订单内容。");

                #endregion
                
                BookOrderModel ret = order;
                if (string.IsNullOrEmpty(order.OrderNo))
                    ret = BookOrderLogic.NewOrder(order);
                else
                    BookOrderLogic.UpdateOrder(order);

                return new JsonEntity<BookOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo += lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<BookOrderModel>(null, errinfo, false);
        }
        [Route("GetOrders")]
        [HttpPost]
        public JsonEntitySet<BookOrderModel> GetOrders(JObject request)
        {
            string errinfo = "no data";
            try
            {
                #region 收集参数
                BookOrderQuery sea = new BookOrderQuery();
                sea.PageSize = request.Value<int>("pageSize");
                sea.PageIndex = request.Value<int>("pageIndex");
                sea.GetCustomer = request.Value<bool>("getCustomer");
                sea.CustomerID = request.Value<int>("customerID");
                sea.OrderNo = request.Value<string>("orderNo");
                sea.GetOperator = request.Value<bool>("getOperator");
                var orderStatus = request.Value<string>("orderStatus");
                if (!string.IsNullOrEmpty(orderStatus))
                    sea.OrderStatus = orderStatus.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                var odb = request.Value<string>("orderDateBefore");
                if (!string.IsNullOrEmpty(odb))
                    sea.OrderDateBefore = DateTime.Parse(odb);
                var oda = request.Value<string>("orderDateAfter");
                if (!string.IsNullOrEmpty(oda))
                    sea.OrderDateAfter = DateTime.Parse(oda);
                var orderMethod = request.Value<string>("orderMethod");
                if (!string.IsNullOrEmpty(orderMethod))
                    sea.Method = orderMethod.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                #endregion

                var ret = BookOrderLogic.GetOrders(sea);
                return new JsonEntitySet<BookOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntitySet<BookOrderModel>(null, errinfo, false);
        }
        [Route("GetOrder")]
        [HttpPost]
        public JsonEntity<BookOrderModel> GetOrder(JObject request)
        {
            string errinfo = "no data";
            try
            {
                var ret = BookOrderLogic.GetOrder(request.Value<string>("orderNo"));
                return new JsonEntity<BookOrderModel>(ret);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonEntity<BookOrderModel>(null, errinfo, false);
        }
        [Route("CancelOrder")]
        [HttpPost]
        public JsonResult<bool> CancelOrder(JObject request)
        {
            string errinfo = "撤消单据失败";
            try
            {
                #region 收集参数
                var orderNo = request.Value<string>("orderNo");
                #endregion

                BookOrderLogic.DeleteOrder(orderNo);
                return new JsonResult<bool>(true);
            }
            catch (Utils.InvoicingException lde)
            {
                errinfo = lde.Message;
            }
            catch (Exception ex)
            {
                errinfo = ex.Message;
                Common.Logger.Error("", ex);
            }
            return new JsonResult<bool>(false, errinfo, false);
        }
    }
}
